package com.henghai.zhenxuan.ui.page.signin;

import static com.henghai.zhenxuan.utils.Utils.getSchemeCalendar;
import static com.blankj.utilcode.util.TimeUtils.getSafeDateFormat;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.data.bean.RankingListBean;
import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.domain.request.PrizeDrawRuleListRequester;
import com.henghai.zhenxuan.domain.request.RankingListRequester;
import com.henghai.zhenxuan.domain.request.SignCountRequester;
import com.henghai.zhenxuan.domain.request.UserInfoRequester;
import com.henghai.zhenxuan.domain.request.UserSignListRequester;
import com.henghai.zhenxuan.ui.page.adapter.RankingListAdapter;
import com.henghai.zhenxuan.utils.HiRes;
import com.henghai.zhenxuan.utils.Utils;
import com.blankj.utilcode.util.TimeUtils;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.henghai.zhenxuan.R;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SignInFragment extends BaseFragment {
    private SignInStates mStates;
    private UserSignListRequester mUserSignListRequester;
    private RankingListAdapter mAdapter;
    private SignCountRequester mSignCountRequester;
    private RankingListRequester mRankingListRequester;
    private static final String TAG = SignInFragment.class.getSimpleName();
    private PageMessenger mMessenger;
    private UserInfoRequester mUserInfoRequester;
    private PrizeDrawRuleListRequester mPrizeDrawRuleListRequester;
    private String lotteryType;

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(SignInStates.class);
        mUserSignListRequester = getFragmentScopeViewModel(UserSignListRequester.class);
        mSignCountRequester = getFragmentScopeViewModel(SignCountRequester.class);
        mRankingListRequester = getFragmentScopeViewModel(RankingListRequester.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
        mUserInfoRequester = getActivityScopeViewModel(UserInfoRequester.class);

        mPrizeDrawRuleListRequester = getFragmentScopeViewModel(PrizeDrawRuleListRequester.class);

    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new RankingListAdapter(getContext());
        return new DataBindingConfig(com.henghai.zhenxuan.R.layout.fragment_sign_in, BR.vm, mStates).addBindingParam(BR.click, new ClickProxy()).addBindingParam(BR.adapter, mAdapter).addBindingParam(BR.listener, new MonthChangeListenerHandler());
    }

    public class MonthChangeListenerHandler implements CalendarView.OnMonthChangeListener {
        String monthStr;

        @Override
        public void onMonthChange(int year, int month) {
            if (month < 10) {
                monthStr = "0" + month;
            }
            mStates.month_day.set(year + "." + monthStr);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        WaitDialog.show("正在加载");
        mUserInfoRequester.getTokenResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(dataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            AppConfig.INSTANCE.getMConfigs().user().set(dataResult.getResult().getData());
            mMessenger.input(new Messages(Messages.EVENT_USERINFO_SUCCESS));
        });

        mUserSignListRequester.getResult().observe(this, httpBeanDataResult -> {
//            WaitDialog.dismiss();
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            mStates.currentMonth.set(new ArrayList<>());
            Map<String, Calendar> map = new HashMap<>();
            int year, month, day;
            for (int i = 0; i < httpBeanDataResult.getResult().getData().getRows().size(); i++) {
                String[] date = httpBeanDataResult.getResult().getData().getRows().get(i).getSignInDate().split("-");
                year = Integer.parseInt(date[0]);
                month = Integer.parseInt(date[1]);
                day = Integer.parseInt(date[2]);
                map.put(getSchemeCalendar(year, month, day, HiRes.INSTANCE.getColor(R.color.selected_theme_color), "签").toString(),
                        getSchemeCalendar(year, month, day, HiRes.INSTANCE.getColor(R.color.selected_theme_color), "签"));
                if (month == Utils.getCurrentMonth()) {
                    mStates.currentMonth.get().add(httpBeanDataResult.getResult().getData().getRows().get(i).getSignInDate());
                }
            }
            mStates.signDays.set(mStates.currentMonth.get().size() + "");
            int lossSignDays = Utils.getDaysInMonth(new Date()) - mStates.currentMonth.get().size();
            mStates.lossSignDas.set(lossSignDays + "");
            mStates.calendarData.set(map);
        });
        mUserSignListRequester.request(this);
        mRankingListRequester.getResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            ArrayList<RankingListBean.RowsBean> rows = httpBeanDataResult.getResult().getData().getRows();
            for (int i = 0; i < rows.size(); i++) {
                rows.get(i).setIndex(String.valueOf(i + 1));
            }
            mStates.rankingList.set(rows);
        });
        mRankingListRequester.request(this);
        mSignCountRequester.getResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            mStates.adCount.set(httpBeanDataResult.getResult().getData());
            if (mStates.isFinish.equals("1") && mStates.adCount.get() <= 0) {
                mUserSignListRequester.request(getViewLifecycleOwner());
                mUserInfoRequester.request(getViewLifecycleOwner());
                TipDialog.show("签到成功", WaitDialog.TYPE.SUCCESS, 2100);
            }
        });


        mPrizeDrawRuleListRequester.getResult().observe(this, dataResult -> {
            WaitDialog.dismiss();
            if (!dataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(dataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            if (dataResult.getResult().getData() != null) {
                for (int i = 0; i < dataResult.getResult().getData().size(); i++) {
                    if (dataResult.getResult().getData().get(i).getPrizeDrawType().equals(lotteryType)) {
                        Bundle bundle = new Bundle();
                        bundle.putString(LotteryFragment.KEY_ID, dataResult.getResult().getData().get(i).getId() + "");
                        bundle.putString(LotteryFragment.KEY_TYPE, dataResult.getResult().getData().get(i).getPrizeDrawType() + "");
                        nav().navigate(R.id.action_mainFragment_to_LotteryFragment, bundle);
                        break;
                    }
                }

            }
        });

    }

    private void getSignCount(String isFinish) {
        mSignCountRequester.request(getViewLifecycleOwner(), isFinish);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getSignCount(mStates.isFinish);
        mMessenger.output(this, messages -> {
            if (messages.eventId == Messages.EVENT_USERINFO_SUCCESS) {
                iniViewData();
            } else if (messages.eventId == Messages.EVENT_SHOW_REWARD_AD_SUCCESS) {//观看完成，再次获取剩余观看次数
                mStates.isFinish = "1";
                getSignCount(mStates.isFinish);
            }
        });
    }

    private void iniViewData() {
        mStates.userPoints.set(Utils.stripTrailingZeros(
                AppConfig.INSTANCE.getMConfigs()
                        .user()
                        .get()
                        .getUserPoints()));
    }

    public class ClickProxy {
        public void lotteryIntegral() {
            WaitDialog.show("加载中...");
            lotteryType = "2";
            mPrizeDrawRuleListRequester.request(getViewLifecycleOwner());
        }

        public void lotteryReward() {
            WaitDialog.show("加载中...");
            lotteryType = "1";
            mPrizeDrawRuleListRequester.request(getViewLifecycleOwner());
        }

        public void signIn() {
            if (AppConfig.INSTANCE.getInnerAdCount() < AppConfig.INSTANCE.getMConfigs().login().get().getPlacementTwoCount()) {
                mMessenger.input(new Messages(Messages.EVENT_SHOW_INNER_AD));
            }
            if (!mStates.currentMonth.get().isEmpty()) {
                if (Utils.isToday(mStates.currentMonth.get().get(mStates.currentMonth.get().size() - 1))) {
                    TipDialog.show("今日已完成签到", WaitDialog.TYPE.WARNING);
                    return;
                }
            }
            if (mStates.adCount.get() > 0) {
                MessageDialog.show("提醒", "还需要观看" + mStates.adCount.get() + "次视频").setOkButton("确定", (messageDialog, view) -> {
                    String mRewardVideoKey = AppConfig.INSTANCE.getMConfigs().login().get().getPlacementIdThree();
                    if (mRewardVideoKey == null || mRewardVideoKey.isEmpty()) {
                        TipDialog.show("暂无广告", WaitDialog.TYPE.WARNING);
                        return false;
                    }
                    mMessenger.input(new Messages(Messages.EVENT_SHOW_REWARD_AD));
                    return false;
                }).setCancelButton("取消");
            } else {
                mUserSignListRequester.request(getViewLifecycleOwner());
                mUserInfoRequester.request(getViewLifecycleOwner());
                TipDialog.show("签到成功", WaitDialog.TYPE.SUCCESS);
            }
        }
    }

    public static class SignInStates extends StateHolder {
        public final State<Map<String, Calendar>> calendarData = new State<>(new HashMap<>());
        public final State<String> month_day = new State<>(TimeUtils.getNowString(getSafeDateFormat("yyyy.MM")));
        public final State<ArrayList<RankingListBean.RowsBean>> rankingList = new State<>(new ArrayList<>());
        public final State<String> userPoints = new State<>("");
        public final State<String> signDays = new State<>("");
        public final State<String> lossSignDas = new State<>("");
        public final State<ArrayList<String>> currentMonth = new State<>(new ArrayList<>());
        public final State<Integer> adCount = new State<>(10);
//        public final State<String> appTabs = new State<>(AppConfig.INSTANCE.getMConfigs().login().get().getPackageTabs());

        public String isFinish = "0";
    }
}
